<template>
  <view class="year-detail-wrapper">
    <!-- 头部导航 -->
    <view class="year-detail-header">
      <view class="header-center">
        <text class="header-title">{{ currentYear }}年大事件</text>
      </view>
      <view class="header-right">
        <view class="year-selector" @click="showYearPicker">
          <text class="selector-text">选择年份</text>
          <text class="selector-icon">▼</text>
        </view>
      </view>
    </view>

    <!-- 年份选择器 -->
    <view class="year-picker-overlay" v-if="showPicker" @click="hidePicker">
      <view class="year-picker-content" @click.stop>
        <view class="picker-header">
          <text class="picker-title">选择年份</text>
          <text class="picker-close" @click="hidePicker">×</text>
        </view>
        <scroll-view class="year-list" scroll-y>
          <view class="year-item" :class="{ active: year === currentYear }" v-for="year in yearList" :key="year" @click="selectYear(year)">
            <text class="year-text">{{ year }}年</text>
            <text class="check-icon" v-if="year === currentYear">✓</text>
          </view>
        </scroll-view>
      </view>
    </view>

    <!-- 事件列表 -->
    <view class="events-content" v-if="!loading && eventList.length > 0">
      <view class="events-list">
        <view class="event-item" v-for="(item, index) in eventList" :key="item.id">
          <view class="event-date">
            <text class="date-text">{{ formatDate(item.dateTime) }}</text>
          </view>
          <view class="event-content">
            <text class="event-title">{{ item.title }}</text>
            <text class="event-text" v-if="item.text">{{ item.text }}</text>

            <!-- 图片列表 -->
            <view class="event-images" v-if="hasImages(item.fileVOList)">
              <view class="image-grid" :class="getImageGridClass(item.fileVOList.length)">
                <image class="event-image" v-for="(file, fileIndex) in item.fileVOList" :key="fileIndex" :src="file.url" :alt="file.name || '事件图片'" mode="aspectFill" @click="previewImage(file.url, item.fileVOList)" />
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-container" v-else-if="!loading && eventList.length === 0">
      <text class="empty-text">{{ currentYear }}年暂无大事件数据</text>
    </view>

    <!-- 加载状态 -->
    <view class="loading-container" v-else>
      <text class="loading-text">加载中...</text>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getListByTime, getListByLevel } from '@/api/majorEvent'

const currentYear = ref('')
const eventList = ref([])
const loading = ref(true)
const showPicker = ref(false)
const yearList = ref([])

// 格式化日期 - 显示月日
const formatDate = (dateStr) => {
  if (!dateStr || typeof dateStr !== 'string') return ''

  const datePart = dateStr.split(' ')[0] // 取 "2021-08-18" 部分
  const [, month, day] = datePart.split('-')

  const monthNum = parseInt(month, 10)
  const dayNum = parseInt(day, 10)

  // 验证月份和日期是否有效
  if (isNaN(monthNum) || isNaN(dayNum) || monthNum < 1 || monthNum > 12 || dayNum < 1 || dayNum > 31) {
    return ''
  }

  return `${month.padStart(2, '0')}.${day.padStart(2, '0')}`
}

// 日期排序比较函数
const compareDates = (a, b) => {
  const dateA = new Date(a.dateTime.replace(/-/g, '/'))
  const dateB = new Date(b.dateTime.replace(/-/g, '/'))

  // 检查日期是否有效
  if (isNaN(dateA.getTime()) || isNaN(dateB.getTime())) {
    return 0
  }
  return dateB - dateA // 最新的在前面
}

// 获取年份事件列表
const getYearEvents = async (year) => {
  if (!year) return

  loading.value = true

  const res = await getListByTime({ majorDate: year })

  if (res?.code === 0 && Array.isArray(res.data)) {
    eventList.value = res.data.sort(compareDates)
  } else {
    eventList.value = []
    console.warn('获取事件列表失败:', res)
  }

  loading.value = false
}

// 默认年份列表
const DEFAULT_YEARS = ['2028', '2027', '2026', '2025', '2024', '2023', '2022', '2021']

// 提取并验证年份
const extractValidYear = (dateTime) => {
  if (!dateTime || typeof dateTime !== 'string') return null

  const year = parseInt(dateTime.split('-')[0], 10)
  return year >= 1900 && year <= 2100 ? year : null
}

// 从API获取年份列表
const generateYearList = async () => {
  const res = await getListByLevel()

  if (res?.code === 0 && Array.isArray(res.data)) {
    // 获取所有有效的年份
    const years = res.data.map((item) => extractValidYear(item.dateTime)).filter((year) => year !== null)

    if (years.length > 0) {
      // 去重并排序（最新年份在前）
      const uniqueYears = [...new Set(years)].sort((a, b) => b - a).map((year) => year.toString())

      yearList.value = uniqueYears
      return
    }
  }

  console.warn('获取年份列表失败，使用默认列表:', res)

  // 使用默认年份列表
  yearList.value = [...DEFAULT_YEARS]
}

// 显示年份选择器
const showYearPicker = () => {
  showPicker.value = true
}

// 隐藏年份选择器
const hidePicker = () => {
  showPicker.value = false
}

// 选择年份
const selectYear = (year) => {
  if (year && year !== currentYear.value) {
    currentYear.value = year
    getYearEvents(year)
  }
  hidePicker()
}

// 图片预览
const previewImage = (current, urls) => {
  if (!current || !Array.isArray(urls)) return

  const imageUrls = urls.filter((file) => file?.url).map((file) => file.url)

  if (imageUrls.length === 0) return

  uni.previewImage({
    current,
    urls: imageUrls
  })
}

// 检查是否有图片
const hasImages = (fileList) => {
  return Array.isArray(fileList) && fileList.length > 0
}

// 获取图片网格样式类
const getImageGridClass = (count) => {
  if (count === 1) return 'single-image'
  if (count === 2) return 'two-images'
  return ''
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 初始化页面数据
const initPageData = async () => {
  // 先获取年份列表
  await generateYearList()

  // 获取页面参数
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const options = currentPage?.options || {}

  // 确定要显示的年份
  const targetYear = options.year || yearList.value[0] || '2028'

  currentYear.value = targetYear
  await getYearEvents(targetYear)
}

onMounted(() => {
  initPageData().catch((error) => {
    console.error('页面初始化失败:', error)
    // 设置默认值确保页面可用
    currentYear.value = '2028'
    yearList.value = [...DEFAULT_YEARS]
  })
})
</script>

<style scoped>
.year-detail-wrapper {
  background-color: #f9f9f9;
  min-height: 100vh;
}

.year-detail-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #e5e5e5;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-left {
  width: 80rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  font-size: 36rpx;
  color: #007aff;
  font-weight: bold;
}

.header-center {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.header-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.header-right {
  width: 180rpx;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.year-selector {
  display: flex;
  align-items: center;
  padding: 8rpx 16rpx;
  background-color: #fbfbfb;
  border-radius: 20rpx;
  border: 1rpx solid #e9ecef;
}

.selector-text {
  font-size: 24rpx;
  color: #007aff;
  margin-right: 8rpx;
}

.selector-icon {
  font-size: 20rpx;
  color: #007aff;
  transition: transform 0.3s ease;
}

.year-picker-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: flex-end;
  justify-content: center;
}

.year-picker-content {
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  width: 100%;
  max-height: 600rpx;
  overflow: hidden;
  box-shadow: 0 -8rpx 32rpx rgba(0, 0, 0, 0.2);
  animation: slideUp 0.3s ease-out;
  padding-bottom: env(safe-area-inset-bottom);
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

.picker-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #e9ecef;
}

.picker-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.picker-close {
  font-size: 40rpx;
  color: #999;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background-color: #fbfbfb;
}

.year-list {
  max-height: 400rpx;
}

.year-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  transition: background-color 0.2s ease;
}

.year-item:hover {
  background-color: #fbfbfb;
}

.year-item.active {
  background-color: #e3f2fd;
}

.year-text {
  font-size: 28rpx;
  color: #333;
}

.year-item.active .year-text {
  color: #007aff;
  font-weight: bold;
}

.check-icon {
  font-size: 32rpx;
  color: #007aff;
  font-weight: bold;
}

.events-content {
  padding: 40rpx 30rpx;
}

.events-list {
  position: relative;
}

.event-item {
  display: flex;
  margin-bottom: 50rpx;
  position: relative;
  align-items: flex-start;
  padding-left: 120rpx;
}

.event-item::before {
  content: '';
  position: absolute;
  left: 94rpx;
  top: 12rpx;
  width: 12rpx;
  height: 12rpx;
  background-color: #007aff;
  border-radius: 50%;
  border: 2rpx solid #fff;
  box-shadow: 0 0 0 2rpx #007aff;
  z-index: 2;
}

.event-item::after {
  content: '';
  position: absolute;
  left: 99rpx;
  top: 24rpx;
  bottom: -50rpx;
  width: 2rpx;
  background-color: #e5e5e5;
  z-index: 1;
}

.event-item:last-child::after {
  display: none;
}

.event-date {
  position: absolute;
  left: 0;
  top: 8rpx;
  width: 80rpx;
  text-align: center;
}

.date-text {
  font-size: 22rpx;
  color: #666;
  font-weight: 500;
  line-height: 1.2;
}

.event-content {
  flex: 1;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
  border-left: 6rpx solid #007aff;
  min-width: 0;
  overflow: hidden;
  margin-left: 16rpx;
}

.event-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  line-height: 1.4;
  margin-bottom: 16rpx;
  display: block;
  word-wrap: break-word;
  overflow-wrap: break-word;
}

.event-text {
  font-size: 26rpx;
  color: #666;
  line-height: 1.6;
  display: block;
  word-wrap: break-word;
  word-break: break-all;
  white-space: pre-wrap;
  overflow-wrap: break-word;
}

.event-images {
  margin-top: 20rpx;
}

.image-grid {
  display: grid;
  gap: 12rpx;
  grid-template-columns: repeat(3, 1fr);
}

.image-grid.single-image {
  grid-template-columns: 1fr;
}

.image-grid.two-images {
  grid-template-columns: repeat(2, 1fr);
}

.event-image {
  width: 100%;
  height: 160rpx;
  border-radius: 12rpx;
  background-color: #f9f9f9;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.event-image:active {
  transform: scale(0.98);
}

.image-grid.single-image .event-image {
  height: 300rpx;
}

.image-grid.two-images .event-image {
  height: 200rpx;
}

.loading-container,
.empty-container {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 150rpx 40rpx;
  background-color: #fff;
  border-radius: 20rpx;
  margin: 40rpx 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.loading-text,
.empty-text {
  font-size: 28rpx;
  color: #999;
  text-align: center;
}

/* 响应式适配 */
@media screen and (max-width: 750rpx) {
  .header-title {
    font-size: 28rpx;
  }

  .event-content {
    padding: 24rpx;
  }

  .event-title {
    font-size: 28rpx;
  }

  .event-text {
    font-size: 24rpx;
  }

  .date-text {
    font-size: 24rpx;
  }

  .event-image {
    height: 140rpx;
  }

  .image-grid.single-image .event-image {
    height: 250rpx;
  }

  .image-grid.two-images .event-image {
    height: 180rpx;
  }
}
</style>
